/*
 * Copyright (C) 2007 Eskil Bylund
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 */

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Net.Sockets;
using System.Threading;

using DCSharp.Backend.Connections;
using DCSharp.Backend.Objects;
using DCSharp.Logging;
using DCSharp.Xml;

namespace DCSharp.Backend.Managers
{
	/// <summary>
	/// The errors that can happen when downloading a list from a <see cref="User"/>.
	/// </summary>
	public enum ListDownloadError
	{
		None,
		ListNotAvailable,
		InvalidList
	}

	/// <summary>
	/// Downloads a <see cref="FileList"/> from a <see cref="User"/>.
	/// </summary>
	public class ListDownloader : Downloader
	{
		private static Logger log = LogManager.GetLogger("Downloader");

		public event EventHandler ListReceived;

		private User user;
		private FileList result;
		private ListDownloadError error;
		private long size;
		private double progress;

		private UserConnection connection;
		private FileStream fileStream;

		private object userLock;

		/// <summary>
		/// Initializes a new <see cref="ListDownloader"/> instance.
		/// </summary>
		/// <param name="user">The <see cref="User"/> to get the list from.</param>
		public ListDownloader(User user)
		{
			if (user == null)
			{
				throw new ArgumentNullException("user");
			}
			this.user = user;

			userLock = new Object();
		}

		#region Properties

		/// <value>
		/// The <see cref="User"/> to get the <see cref="FileList"/> from.
		/// </value>
		public User User
		{
			get { return user; }
		}

		/// <value>
		/// The size of the users <see cref="FileList"/> in bytes.
		/// </value>
		public override long FileSize
		{
			get { return size; }
		}

		/// <value>
		/// The progress of the loading of the <see cref="FileList"/> once it's
		/// been received.
		/// </value>
		public double LoadingProgress
		{
			get
			{
				lock (StateLock)
				{
					if (State == DownloadState.Done && fileStream != null)
					{
						// TODO: Remove the try..catch block once SharpZipLib
						// has been updated and provides the IsStreamOwner property.
						try
						{
							progress = (double)fileStream.Position / fileStream.Length;
						}
						catch {}
					}
				}
				return progress;
			}
		}

		/// <value>
		/// The downloaded <see cref="FileList"/>.
		/// </value>
		public FileList Result
		{
			get { return result; }
			private set
			{
				result = value;
				OnListReceived();
			}
		}

		public ListDownloadError Error
		{
			get { return error; }
			private set { error = value; }
		}

		public override object UserLock
		{
			get { return userLock; }
		}

		internal override IEnumerable<User> InterestingUsers
		{
			get { yield return user; }
		}

		#endregion

		#region Methods

		public override void Stop()
		{
			lock (StateLock)
			{
				base.Stop();

				if (connection != null)
				{
					connection.Disconnect();
				}
				Reset();
			}
		}

		public override string ToString()
		{
			return "List from " + user.ToString();
		}

		protected virtual void OnListReceived()
		{
			if (ListReceived != null)
			{
				ListReceived(this, EventArgs.Empty);
			}
		}

		#region Request

		protected override void RequestConnections()
		{
			lock (StateLock)
			{
				if (State == DownloadState.Idle &&
					OnConnectionRequest(user, RequestCallback))
				{
					log.Info("Requested a connection", null, this);
				}
			}
		}

		internal override void HandleIdleUser(User user)
		{
			if (user == this.user)
			{
				RequestConnections();
			}
		}

		private void RequestCallback(User user, bool success)
		{
			if (!success)
			{
				RequestConnections();
			}
		}

		#endregion

		#region Download

		internal override bool Use(UserConnection connection)
		{
			lock (StateLock)
			{
				if (State != DownloadState.Idle || connection.RemoteUser != user)
				{
					return false;
				}
				if (!connection.Supports(RequestType.List))
				{
					HandleNotSupported();
					return false;
				}
				this.connection = connection;

				log.Info("Downloading", null, this);

				// Open the output stream
				try
				{
					fileStream = new FileStream(Path.GetTempFileName(),
						FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.Read);
				}
				catch (Exception e)
				{
					log.Error("Error opening the temp file", e, this);
					StopWithException(e);

					Reset();
					return false;
				}

				// Download the list
				try
				{
					connection.Download(new ListRequest(true), HandleData, connection);
					connection.TransferAborted += OnTransferAborted;

					State = DownloadState.Active;
					return true;
				}
				catch (Exception e)
				{
					log.Error("Error downloading list", e, this);

					Reset();
					throw;
				}
			}
		}

		private void HandleData(byte[] buffer, int offset, int count,
			long remaining, object context)
		{
			if (size == 0)
			{
				size = count + remaining;
			}
			lock (StateLock)
			{
				if (State != DownloadState.Active)
				{
					return;
				}
				try
				{
					fileStream.Write(buffer, offset, count);

					Progress = (double)fileStream.Position / size;
					UpdateMonitor(count);

					if (remaining == 0)
					{
						log.Info("Download complete", null, this);
						State = DownloadState.Loading;

						// Load the list in another thread so that the connection
						// can be use by another downloader.
						ThreadPool.QueueUserWorkItem(CreateFileList, fileStream);
					}
				}
				catch (Exception e)
				{
					log.Error("Error writing data.", e, this);
					StopWithException(e);

					Reset();
					throw;
				}
			}
		}

		private void CreateFileList(object state)
		{
			FileStream fileStream = (FileStream)state;
			try
			{
				fileStream.Position = 0;
				Result = FileList.Create(fileStream, FileUtil.Compression.BZip2,
					user);
				progress = 1;
			}
			catch (Exception e)
			{
				log.Error("Error opening the list", e, user.Uid);
				lock (StateLock)
				{
					if (State != DownloadState.Stopped)
					{
						Error = ListDownloadError.InvalidList;
						StopWithException(e);
					}
				}
			}
			finally
			{
				lock (StateLock)
				{
					if (State == DownloadState.Loading)
					{
						State = DownloadState.Done;
					}
					Reset();
				}
			}
		}

		private void Reset()
		{
			if (fileStream != null)
			{
				if (File.Exists(fileStream.Name))
				{
					File.Delete(fileStream.Name);
				}
				fileStream.Close();
				fileStream = null;
			}
			if (connection != null)
			{
				connection.TransferAborted -= OnTransferAborted;
				connection = null;
			}

			if (State == DownloadState.Active)
			{
				State = DownloadState.Idle;
				RequestConnections();
			}
		}

		private void HandleNotSupported()
		{
			log.Error("User does not support list uploads.", null, this);

			Error = ListDownloadError.ListNotAvailable;
			State = DownloadState.Stopped;
		}

		private void OnTransferAborted(object obj, TransferErrorEventArgs args)
		{
			log.Error("Transfer aborted: " + args.Error + " - " + args.Message, null, this);
			lock (StateLock)
			{
				if (args.Error == TransferError.NotAvailable)
				{
					HandleNotSupported();
				}
				Reset();
			}
		}

		#endregion

		#endregion
	}
}
